import { HTTP } from '../util/http.js'

class ClassicModel extends HTTP{
  getLatest(sCallback){//首页数据请求 继承
    this.request({
      url: 'classic/latest',
      success: (res) => {
        console.log(res)
        sCallback(res)
        this._setLatestIndex(res.index)
        //初始设置缓存
        let key=this._getKey(res.index)
        wx.setStorageSync(key, res)
      }
    })
  }
  //下一页
  //navi 左右请求 上一页
  getClassic(index,nextOrPrevious,sCallback) {
    //先重缓存中寻找 or API=>写入缓存
    //key 确定key
    let key = nextOrPrevious == 'next' ? this._getKey(index + 1) : this._getKey(index - 1)
    let classic=wx.getStorageSync(key)
    if(!classic){
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,
        success:(res)=>{
          wx.setStorageSync(this._getKey(res.index), res)
          sCallback(res)
        }
      })
    }else{
      sCallback(classic)
    }
  }
  //是否是第一个
  isFirst(index){
    return index==1?true:false
  }
  //是否是最后一个
  isLatest(index){
    let LatestIndex=this._getLatestIndex()
    return LatestIndex == index ? true : false
  }

  //流行页面请求喜欢数据
  getMyFavor(success){
    const params={
      url:'classic/favor',
      success:success
    }
    this.request(params)
  }


  //写入缓存
  _setLatestIndex(index){
    //同步写入缓冲 异步去掉Sync
    wx.setStorageSync('latest', index)
  }

 //读取缓存 
  _getLatestIndex(){
    let index = wx.getStorageSync('latest')
    return index
  }
 
 //key 确定key
 _getKey(index){
   let key='classic-'+index
   return key
 }

}
export { ClassicModel }